package cn.wolfcode.wolf2world.service.impl;

import cn.wolfcode.wolf2world.domain.Region;
import cn.wolfcode.wolf2world.query.QueryObject;
import cn.wolfcode.wolf2world.repository.RegionRepository;
import cn.wolfcode.wolf2world.service.RegionService;
import cn.wolfcode.wolf2world.utils.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author 杨兴健
 * @Date 2020/8/9 20:09
 */
@Service
public class RegionServiceImpl implements RegionService {
    @Autowired
    private RegionRepository regionRepository;

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void save(Region region) {
        region.setId(null);
        regionRepository.insert(region);
    }

    @Override
    public void update(Region region) {
        regionRepository.save(region);
    }

    @Override
    public void delete(String id) {
        regionRepository.deleteById(id);
    }

    @Override
    public Region get(String id) {
        return regionRepository.findById(id).orElse(null);
    }

    @Override
    public List<Region> list() {
        return regionRepository.findAll();
    }

    @Override
    public Page<Region> query(QueryObject qo) {

        //查询对象，具有查询的所有信息，包括筛选条件，排序，返回数量等
        Query query = new Query();

        return DBHelper.getPage(mongoTemplate, query, qo, Region.class, Sort.Direction.ASC, "sequence");
    }

    /**
     * 新增或编辑区域
     * @param region
     */
    @Override
    public void saveOrUpdate(Region region) {
        if (StringUtils.hasLength(region.getId())) {
            //编辑
            this.update(region);
        }else {
            //新增
            this.save(region);
        }
    }

    /**
     * 更改区域热度
     * @param hot
     * @param id
     */
    @Override
    public void changeHotValue(Integer hot, String id) {
        //全量更新
        Region region = this.get(id);
        region.setIshot(hot);
        this.update(region);
    }

    /**
     * 查询热区域
     * @return
     */
    @Override
    public List<Region> hotRegion() {
        return regionRepository.findByIshot(Region.STATE_HOT);
//        return mongoTemplate.find(Query.query(Criteria.where("ishot").is(Region.STATE_HOT)), Region.class);
    }
}
